package com.cyx.netty.gateway.client.channel;

import com.cyx.netty.gateway.support.ServerWebExchange;
import com.cyx.netty.gateway.util.cache.ChannelCacheManager;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

@Slf4j
class HeartBeatClientHandler extends ChannelInboundHandlerAdapter {
  private int lossConnectCount = 0;
  private ServerWebExchange serverWebExchange;

  public HeartBeatClientHandler(ServerWebExchange serverWebExchange) {
    this.serverWebExchange = serverWebExchange;
  }

  @Override
  public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

    log.info("已经**秒未收到客户端的消息了！");
    if (evt instanceof IdleStateEvent){
      IdleStateEvent event = (IdleStateEvent)evt;
      if (event.state()== IdleState.READER_IDLE){
        lossConnectCount++;
        if (lossConnectCount>3){

          ChannelCacheManager.remove(serverWebExchange.getChannelHandlerContext().channel().id().asShortText());
          log.info("关闭这个不活跃通道！");
          ctx.channel().close();
        }
      }
    }else {
      super.userEventTriggered(ctx,evt);
    }
  }

  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    lossConnectCount = 0;
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    ctx.close();
  }
}
